package com.nebula.maven.springbootmebula.nebula;

import com.vesoft.nebula.client.graph.NebulaPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import com.vesoft.nebula.client.graph.net.NebulaPool;
import com.vesoft.nebula.client.graph.net.Session;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Configuration
@Data
public class NebulaGraphConfig {

    @Value("${nebula.graphd.addresses}")
    private String addresses;

    @Value("${nebula.username}")
    private String username;

    @Value("${nebula.password}")
    private String password;

    @Value("${nebula.space}")
    private String space;

    private Integer maxSession = 20;
    private Integer minSession = 1;

    @Bean
    public NebulaPool nebulaPool() throws Exception {
        NebulaPoolConfig poolConfig = new NebulaPoolConfig();
        List<HostAddress> addressList = Arrays.stream(addresses.split(","))
                .map(addr -> {
                    String[] parts = addr.split(":");
                    return new HostAddress(parts[0], Integer.parseInt(parts[1]));
                })
                .toList();
        NebulaPool pool = new NebulaPool();
        pool.init(addressList, poolConfig);
        return pool;
    }


    public Session session(NebulaPool nebulaPool) throws Exception {
        Session session = nebulaPool.getSession(username, password, true);
        session.execute("USE " + space);
        return session;
    }
}